//
//  CTView.m
//  CTView
//
//  Created by 王欣 on 2018/1/19.
//  Copyright © 2018年 北大方正电子有限公司. All rights reserved.
//

#import "CTView.h"
#import <CoreText/CoreText.h>

@interface CTView()
@property(nonatomic,strong)UIImageView * labelImageView;
@property (nonatomic, strong) UIFont *font;


@end


@implementation CTView


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setupSubviews];
        self.font = [UIFont systemFontOfSize:18];
    }return self;
}
-(void)setupSubviews{
    self.labelImageView = [[UIImageView alloc] init];
    self.labelImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.labelImageView.tag = NSIntegerMin;
    self.labelImageView.clipsToBounds = YES;
    [self addSubview:self.labelImageView];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    self.labelImageView.frame = self.bounds;
    [self draw];
}

-(void)setAttributeStr:(NSMutableAttributedString *)attributeStr{
       _attributeStr = attributeStr;
    if (self.bounds.size.width==0||self.bounds.size.height==0) {
        return;

    }
    [self draw];
}
-(void)draw{
    if (self.bounds.size.width==0||self.bounds.size.height==0) {
        return;
    }
    __block  CGRect rect = self.bounds;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        if (context==NULL) {
            return;
        }
        [self drawattributedString:self.attributeStr textRange:CFRangeMake(0, self.attributeStr.length) inRect:rect context:context];
        
        UIImage *screenShotimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        dispatch_async(dispatch_get_main_queue(), ^{
            self.labelImageView.image = screenShotimage;
        });
        
    });
}



//确保行高一致，计算所需触摸区域
- (void)drawattributedString:(NSAttributedString *)attributedString
                   textRange:(CFRange)textRange
                      inRect:(CGRect)rect
                     context:(CGContextRef)c
{
    //如果是竖版显示
    if (self.verticalForm) {
        if (self.text==nil||self.text.length==0) {
            return;
        }
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        [dict setValue:[UIFont systemFontOfSize:self.fontSize] forKey:NSFontAttributeName];
        [dict setValue:self.fontColor forKey:NSForegroundColorAttributeName];
        CGFloat viewHeight = rect.size.height;
        if (viewHeight>10) {
            viewHeight -= 10;
        }
        CGFloat width = rect.size.width;
        CGFloat lineWidth   = self.fontSize + self.lineGap;
        CGFloat lineHeight  = self.fontSize + self.knerGap;
        NSInteger count     = floor(viewHeight/lineHeight);//计算出一列容的字数
        NSInteger lineCount = ceilf(self.text.length/(CGFloat)count);
        BOOL firstSymbol = NO;
        for (int i = 0; i< lineCount; i++) {
            for (int j = 0; j< count; j++) {
                NSInteger index = i * count + j;
                if (index+1>self.text.length) {
                    return;
                }
                NSString * str = [self.text substringWithRange:NSMakeRange(index, 1)];
                if (j==0) {
                    if (([str isEqualToString:@"，"]|[str isEqualToString:@"。"])&&i!=0) {
                        
                        firstSymbol = YES;
                        CGRect strRect = CGRectMake(width - lineWidth *i+5, lineHeight * count -10, lineWidth, lineHeight);
                        [str drawInRect:strRect withAttributes:dict];
                        
                    }else{
                        
                        [str drawInRect:CGRectMake(width - lineWidth *(i+1), lineHeight * j, lineWidth, lineHeight) withAttributes:dict];
                        firstSymbol = NO;
                    }
                    
                }else{
                    int newJ = j;
                    if (firstSymbol) {
                        newJ = j -1;
                    }
                    if ([str isEqualToString:@"，"]|[str isEqualToString:@"。"]|[str isEqualToString:@"；"]|[str isEqualToString:@"、"]|[str isEqualToString:@"："]|[str isEqualToString:@"』"]|[str isEqualToString:@"？"]|[str isEqualToString:@":"]) {
                        
                        [str drawInRect:CGRectMake(width - lineWidth *(i+1) + lineWidth/4, lineHeight * newJ - lineHeight /4, lineWidth, lineHeight) withAttributes:dict];
                        
                    }else{
                        
                        [str drawInRect:CGRectMake(width - lineWidth *(i+1), lineHeight * newJ, lineWidth, lineHeight) withAttributes:dict];
                        
                    }
                }
                
            }
        }
        
        
    }else{
        if (self.attributeStr.string.length==0||self.attributeStr==nil) {
            return;
        }
        CGContextSetTextMatrix(c,CGAffineTransformIdentity);
        CGContextTranslateCTM(c,0,rect.size.height);
        CGContextScaleCTM(c,1.0,-1.0);
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, rect);
        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
        CTFrameRef frame = CTFramesetterCreateFrame(framesetter, textRange, path, NULL);
        if (!frame) {
            return;
        }
        CTFrameDraw(frame, c);
        CFRelease(frame);
        CFRelease(frame);
        CFRelease(path);
    }
}
+(CGFloat)returnTextWidthWith:(NSString*)str lineGap:(CGFloat)lineGap knetGap:(CGFloat)knerGap fonSize:(CGFloat)fontSize MaxHeight:(CGFloat)height{
    CGFloat width = 0;
    CGFloat lineWidth  = fontSize + lineGap;
    CGFloat lineHeight = fontSize + knerGap;
    if (height>10) {
        height -= 10;
    }
    NSInteger count     = floor(height/lineHeight);//计算出一列容的字数
    NSInteger lineCount = ceilf(str.length/(CGFloat)count);
    width += lineCount * lineWidth ;
    return width;
}

+(CGFloat)returnSingleLineTextHeight:(NSString*)str lineGap:(CGFloat)lineGap knetGap:(CGFloat)knerGap fonSize:(CGFloat)fontSize MaxHeight:(CGFloat)height{
    
    CGFloat lineHeight = fontSize + knerGap;
    CGFloat Totalheight = str.length * lineHeight + 10;
    return Totalheight;
}

@end

